package com.ciba.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciba.demo.mapper.UserInfoMapper;
import com.ciba.demo.pojo.UserInfo;
import com.ciba.demo.respone.ApiRestResponse;
import com.ciba.demo.service.RegisterService;
import com.ciba.demo.service.SendJunkMailService;
import com.ciba.demo.util.KeyUtils;
import com.ciba.demo.util.RecordingUtils;
import com.ciba.demo.util.SessionUtils;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Wrapper;

@Repository
public class RegisterServiceImple implements RegisterService {
    @Autowired
    SendJunkMailService sendJunkMailService ;

    @Autowired
    UserInfoMapper userInfoMapper ;

    @Override
    public ApiRestResponse getCode(HttpServletRequest request, HttpServletResponse response) {
        String email = request.getParameter("Email");
        String key = KeyUtils.getKey() ;
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>() ;
        wrapper.eq(true,"email",email);
        UserInfo user = userInfoMapper.selectOne(wrapper) ;
        if(user!=null){
            return  ApiRestResponse.error().setStatus(-1).setMsg("已被注册") ;
        }
        if (sendJunkMailService.sendJunkMail(email,key) ) {
            SessionUtils.addCode(email,key);
            System.out.println(key) ;
            return ApiRestResponse.success().setStatus(1).setMsg("发送成功");
        }
        return ApiRestResponse.error().setStatus(0).setMsg("发送失败");
    }

    @Override
    public ApiRestResponse register(HttpServletRequest request, HttpServletResponse response) {
        String email = request.getParameter("email") ;
        String passWord = request.getParameter("passWord") ;
        String code = request.getParameter("code") ;
        String name = request.getParameter("name") ;
        UserInfo userInfo = new UserInfo() ;
        userInfo.setName(name);
        userInfo.setEmail(email);
        userInfo.setPassword(passWord);
        if(code.equals(SessionUtils.getCode(email))){
            if(userInfoMapper.insert(userInfo) ==1)
                return ApiRestResponse.success().setStatus(1).setMsg("注册成功");
            else
                return ApiRestResponse.error().setStatus(0).setMsg("注册失败！") ;
        }else{
            return ApiRestResponse.error().setStatus(-1).setMsg("验证码/邮箱有误！") ;
        }
    }
}
